package com.watson.spring.all.security.service.security;

import com.watson.spring.all.security.base.tool.Rdad;
import com.watson.spring.all.security.base.tool.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author watson
 * @date 2021/5/28 14:17
 * @Description: 退出处理器，退出删除token
 **/
public class TokenLogoutHandler implements LogoutHandler {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Authentication authentication) {
        //从header里面获取token
        //token不为空，从redis移除token
        String token = request.getHeader("token");
        if (token != null) {
            tokenManager.removeToken(token);
            //从token里面获取用户名
            String userInfoForToken = tokenManager.getUserInfoForToken(token);
            redisTemplate.delete(userInfoForToken);

            ResponseUtil.out(response, Rdad.ok());
        }

    }
}
